<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="小程序名称">
                <a-input placeholder="请输入小程序名称" v-model="queryParam.app_name" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="getList">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>

    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.is_use" @change="getList">
          <a-radio-button :value="0"> 全部 </a-radio-button>
          <a-radio-button :value="1"> 已使用 </a-radio-button>
          <a-radio-button :value="2"> 未使用 </a-radio-button>
        </a-radio-group>

        <a-button v-if="!hasChannel" type="primary" @click="$router.push('/setting/appletManagement/chooseType?type=1')"
          >+ 新增</a-button
        >
        <a-button v-else type="primary" @click="$router.push('/saasChannel/appletManagement/chooseType?type=1')"
          >+ 新增</a-button
        >
      </div>
      <a-table
        :rowKey="
          (r, i) => {
            return i
          }
        "
        :pagination="{
          total: this.totalCount,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
        :columns="columns"
        :data-source="list"
      >
        <div slot="user" slot-scope="scope">
          <div class="name">
            <div class="pic">
              <img :src="scope.app_logo" alt="" v-if="scope.app_logo" />
              <img src="../../assets/images/defaultMini.png" alt="" v-else />
            </div>
            <div class="info">
              <span v-if="scope.app_name">{{ scope.app_name }}</span>
              <span v-else>恭喜您成功注册小程序</span>
              <span v-if="scope.category_name">{{ scope.category_name }}</span>
              <span v-else>点击审核提交资料发布小程序</span>
            </div>
          </div>
        </div>
        <div slot="status" slot-scope="scope">
          <!-- <span v-if="scope.is_submit == -2">已拒绝</span>
          <span v-if="scope.is_submit == -1">待确认</span>
          <span v-if="scope.is_submit == 0">未审核</span>
          <span v-if="scope.is_submit == 1">审核中</span>
          <span v-if="scope.is_submit == 2">审核通过</span>
          <span v-if="scope.is_submit == 3">审核失败</span>
          <span v-if="scope.is_submit == 4">已发布</span> -->

          <div class="status">
            <span :style="getStatus(scope.is_submit)[0]"></span>
            <span>{{ getStatus(scope.is_submit)[1] }}</span>
          </div>
        </div>

        <span slot="created_at" slot-scope="text">
          {{ text > 0 ? $moment(text * 1000).format('YYYY-MM-DD HH:mm:ss') : '-' }}
        </span>

        <span slot="is_use" slot-scope="text">
          <a-switch
            v-if="text.is_submit == 4 && text.is_use === '2'"
            :checked="text.is_use"
            @change="useApplet(text.id)"
            checkedValue="1"
            unCheckedValue="2"
            checkedChildren="开"
            unCheckedChildren="关"
          >
          </a-switch>
          <span v-else>-</span>
        </span>

        <div slot="action" slot-scope="scope" class="action">
          <!-- <a-button
            @click="alipayInfo(scope.id)"
            :disabled="scope.is_submit == -1"
            type="link"
            v-if="scope.is_submit == 0 || scope.is_submit == 3 || scope.is_submit == -1"
            >审核</a-button
          > -->

          <!-- <a-button @click="cancleApply(scope.id)" type="link" v-if="scope.is_submit == 1">取消</a-button> -->
          <!-- <a-button @click="issueAlipay(scope.id)" type="link" v-if="scope.is_submit == 2">发布</a-button> -->
          <!-- <a-button @click="promotionAlipay(scope.id)" type="link" v-if="scope.is_submit == 4">二维码</a-button> -->
          <!-- <a-button
            @click="$router.push('/setting/appletManagement/writeInformation?type=1&id=' + scope.id)"
            type="link"
            v-if="scope.is_submit == -2"
            >填写</a-button
          > -->

          <a-button @click="see(scope.id)" :disabled="false && scope.mini_status === 0" type="link">查看</a-button>
          <a-divider type="vertical" />
          <!-- :disabled="scope.is_submit == -1 || scope.is_submit == -2" -->
          <a-dropdown :disabled="false && scope.mini_status === 0">
            <a-button type="link"> 更多 <a-icon type="down" /> </a-button>
            <a-menu slot="overlay">
              <a-menu-item
                v-if="scope.is_submit == 0 || scope.is_submit == 3 || scope.is_submit == -1"
                @click="alipayInfo(scope.id)"
                :disabled="scope.is_submit == -1"
              >
                <a href="javascript:;">提交审核</a>
              </a-menu-item>
              <a-menu-item @click="cancleApply(scope.id)" v-if="scope.is_submit == 1">
                <a href="javascript:;">取消</a>
              </a-menu-item>
              <a-menu-item @click="issueAlipay(scope.id)" v-if="scope.is_submit == 2">
                <a href="javascript:;">发布</a>
              </a-menu-item>
              <a-menu-item @click="promotionAlipay(scope.id)" v-if="scope.is_submit == 4">
                <a href="javascript:;">二维码</a>
              </a-menu-item>
              <a-menu-item @click="previewAlipay(scope)" v-if="scope.is_submit == 0">
                <a href="javascript:;">{{ scope.is_experience == 0 ? '设为体验版' : '体验版二维码' }}</a>
              </a-menu-item>
              <a-menu-item @click="useApplet(scope.id)" v-if="scope.is_submit == 4 && scope.is_use == 2">
                <a href="javascript:;">使用小程序</a>
              </a-menu-item>
              <a-menu-item @click="rollbackAlipay(scope.id)" v-if="scope.is_submit == 3 || scope.is_submit == 2">
                <a href="javascript:;">回退开发</a>
              </a-menu-item>
              <a-menu-item @click="cancleExperience(scope.id)" v-if="scope.is_experience == 1">
                <a href="javascript:;">取消体验版</a>
              </a-menu-item>
              <a-menu-item @click="update(scope.id)" v-if="scope.is_submit != -1 || scope.is_submit != -2">
                <a href="javascript:;">更新模板</a>
              </a-menu-item>
              <a-menu-item @click="faceBind(scope.id)">
                <a
                  href="javascript:;"
                  v-if="scope.batch_status == 0 || scope.batch_status == 1 || scope.batch_status == 4"
                  >创建事务</a
                >
                <a href="javascript:;" v-if="scope.batch_status == 7">提交审核</a>
                <a href="javascript:;" v-if="scope.batch_status == 3">事务审核中</a>
                <a href="javascript:;" v-if="scope.batch_status == 5">待商户确认</a>
                <a href="javascript:;" v-if="scope.batch_status == 6">已完成</a>
                <a href="javascript:;" v-if="scope.batch_status == 8">审核失败</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </div>

        <div slot="experience" slot-scope="scope">
          <a-tag color="green" v-if="scope.is_experience == 1">是</a-tag>
          <a-tag color="gray" v-if="scope.is_experience == 0">否</a-tag>
        </div>

        <div slot="shop_status" slot-scope="scope">
          <a-tag :color="getShopStatus(scope.shop_status)[0]">{{ getShopStatus(scope.shop_status)[1] }}</a-tag>
        </div>

        <!-- <div slot="authorization" slot-scope="scope">
          <a-button v-if="!scope.is_get_phone" @click="toAuthorization(scope)">点击授权</a-button>
          <span v-if="scope.is_get_phone == 1">
            授权中
          </span>
          <span v-if="scope.is_get_phone == 2">
            已授权
          </span>
          <a-button v-if="scope.is_get_phone == 3" @click="toAuthorization(scope)">点击授权</a-button>
        </div> -->

        <div slot="mini_status" slot-scope="scope">
          <a-tag :color="getMiniStatus(scope.mini_status)[0]">{{ getMiniStatus(scope.mini_status)[1] }}</a-tag>
        </div>

        <div slot="bind_face" slot-scope="scope">
          <a-tag :color="getBindFace(scope.batch_status)[0]">{{ getBindFace(scope.batch_status)[1] }}</a-tag>

          <!-- <a-button
            href="javascript:;"
            v-if="scope.batch_status == 0 || scope.batch_status == 1 || scope.batch_status == 4"
            @click="faceBind(scope.id)"
            >创建事务</a-button
          >
          <a-button
            href="javascript:;"
            v-if="scope.batch_status == 2 || scope.batch_status == 7"
            @click="faceBind(scope.id)"
            >提交审核</a-button
          >
          <span v-if="scope.batch_status == 3">事务审核中</span>
          <span v-if="scope.batch_status == 5">待商户确认</span>
          <span v-if="scope.batch_status == 6">已完成</span>
          <a-button href="javascript:;" v-if="scope.batch_status == 8" @click="faceBind(scope.id)">审核失败</a-button> -->
        </div>
      </a-table>
    </a-card>

    <!-- 上传代码弹窗 -->
    <a-modal v-model="showUpload" title="上传代码" @ok="uploadApplet" :afterClose="closeModal">
      <a-form-model
        ref="checkForm"
        :model="checkForm"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        :destroyOnClose="true"
      >
        <a-form-model-item label="小程序版本号" prop="user_version">
          <a-input v-model="checkForm.user_version"></a-input>
        </a-form-model-item>
        <a-form-model-item label="小程序代码描述" prop="user_desc">
          <a-textarea v-model="checkForm.user_desc" placeholder="小程序描述" :rows="4" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 提交审核弹窗 -->
    <a-modal v-model="showCheck" title="提交审核" :confirmLoading="isLoading" :width="1000">
      <a-form-model
        ref="ruleForm"
        :model="checkForm"
        :rules="checkRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <div class="formBox">
          <div class="basic">
            <a-form-model-item label="小程序版本号">
              <a-input v-model="checkForm.version" disabled />
            </a-form-model-item>
            <a-form-model-item label="logo" prop="app_logo">
              <cyyUploadImg
                @uploadSuccess="(e) => (checkForm.app_logo = e.data)"
                @deleteImg="checkForm.app_logo = ''"
                :imgSrc="checkForm.app_logo"
              >
              </cyyUploadImg>
            </a-form-model-item>
            <a-form-model-item label="小程序名称" prop="app_name">
              <a-input placeholder="请输入小程序名称" v-model="checkForm.app_name" />
            </a-form-model-item>
            <a-form-model-item label="小程序英文名称" prop="app_english_name">
              <a-input placeholder="请输入小程序英文名称" v-model="checkForm.app_english_name" />
            </a-form-model-item>
            <a-form-model-item label="小程序类目" prop="mini_category_ids">
              <a-tree-select
                style="width: 100%"
                v-model="checkForm.mini_category_ids"
                placeholder="请选择类目"
                allow-clear
                multiple
                @change="changeNode"
              >
                <a-tree-select-node
                  :value="item1.category_id"
                  :title="item1.category_name"
                  v-for="item1 in categories"
                  :key="item1.category_id"
                  :selectable="!item1.has_child"
                >
                  <template v-if="item1.has_child">
                    <a-tree-select-node
                      :value="item1.category_id + '_' + item2.category_id"
                      :title="item2.category_name"
                      v-for="item2 in item1.children"
                      :key="item2.category_id"
                      :selectable="!item2.has_child"
                    >
                      <template v-if="item2.has_child">
                        <a-tree-select-node
                          :value="item1.category_id + '_' + item2.category_id + '_' + item3.category_id"
                          :title="item3.category_name"
                          v-for="item3 in item2.children"
                          :key="item3.category_id"
                          :selectable="!item3.has_child"
                        />
                      </template>
                    </a-tree-select-node>
                  </template>
                </a-tree-select-node>
              </a-tree-select>
            </a-form-model-item>
            <a-form-model-item label="客服电话" prop="service_phone">
              <a-input placeholder="请输入客服电话" v-model="checkForm.service_phone" />
            </a-form-model-item>
            <a-form-model-item label="客服邮箱" prop="service_email">
              <a-input placeholder="请输入客服邮箱" v-model="checkForm.service_email" />
            </a-form-model-item>
            <a-form-model-item label="小程序功能描述" prop="app_slogan">
              <a-input placeholder="请输入小程序功能描述" v-model="checkForm.app_slogan" />
            </a-form-model-item>
            <a-form-model-item label="小程序应用描述" prop="app_desc">
              <a-textarea placeholder="请输入小程序应用描述" :rows="3" v-model="checkForm.app_desc" />
            </a-form-model-item>
            <a-form-model-item label="企业名称" prop="license_name">
              <a-input placeholder="请输入企业名称" v-model="checkForm.license_name" />
            </a-form-model-item>
            <a-form-model-item label="企业代码" prop="license_no">
              <a-input placeholder="请输入企业代码" v-model="checkForm.license_no" />
            </a-form-model-item>
            <a-form-model-item label="营业执照" prop="license_pic">
              <cyyUploadImg
                @uploadSuccess="(e) => (checkForm.license_pic = e.data)"
                @deleteImg="checkForm.license_pic = ''"
                :imgSrc="checkForm.license_pic"
              >
              </cyyUploadImg>
            </a-form-model-item>
            <a-form-model-item label="是否长期" prop="service_phone">
              <a-radio-group v-model="checkForm.is_long_effective">
                <a-radio value="0"> 短期 </a-radio>
                <a-radio value="1"> 长期 </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="过期时间" prop="license_date" v-if="checkForm.is_long_effective == 0">
              <a-date-picker v-model="checkForm.license_date" valueFormat="YYYY-MM-DD" />
            </a-form-model-item>
          </div>
          <div class="version">
            <a-form-model-item label="小程序版本描述" prop="version_desc">
              <a-textarea placeholder="请输入小程序版本描述" :rows="3" v-model="checkForm.version_desc" />
            </a-form-model-item>
            <a-form-model-item label="特殊资质证书" prop="other_data">
              <cyyUploadImg
                @uploadSuccess="selectPic"
                @deleteImg="delPic"
                :imgList.sync="checkForm.other_data"
                dataType="list"
              >
              </cyyUploadImg>
            </a-form-model-item>
          </div>
        </div>
      </a-form-model>
      <div slot="footer" style="display: flex; justify-content: flex-end">
        <a-button @click="showCheck = false">取消</a-button>
        <a-button type="primary" @click="update(checkForm.id)">更新模板</a-button>
        <a-button type="primary" @click="cancelAudit(checkForm.id)" v-if="checkForm.is_submit == 1">撤销审核</a-button>
        <a-button type="primary" @click="checkApplet" v-else>提交审核</a-button>
      </div>
    </a-modal>
    <a-modal v-model="showPreview" title="预览小程序" :width="700" @ok="showPreview = false" :afterClose="closeModal">
      <div class="qrBox">
        <div class="qrCode">
          <img :src="qrCode" alt="" />
        </div>
        <div class="add">
          <p>添加小程序体验者：</p>
          <a-input-search
            v-model="wechatId"
            enter-button="添加"
            placeholder="请输入支付宝账号"
            @search="addPreviewer"
            style="margin: 24px 0"
          />
          <p>添加体验者权限后，被添加的账号前往支付宝信息中心确认体验者邀请。否则不会生效！</p>
          <a-button type="link" @click="downloadIamge(qrCode, '小程序码')">下载小程序码</a-button>
        </div>
      </div>
    </a-modal>
    <a-modal v-model="showQrcode" title="小程序二维码" @ok="showQrcode = false">
      <div class="qrBox">
        <div class="qrCode">
          <img :src="qrcodeUrl" alt="" />
        </div>
      </div>
    </a-modal>
    <!-- 授权手机号弹窗 -->
    <a-modal v-model="showAuthorization" title="授权手机号" @ok="applyAuth" :confirmLoading="isLoading" :width="800">
      <a-form-model
        ref="authForm"
        :model="authForm"
        :rules="authRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-model-item label="上传内容" prop="pics">
          <cyyUploadImg @uploadSuccess="successCb" @deleteImg="deleteCb" :imgList="authForm.picture" dataType="list">
          </cyyUploadImg>
          <cyyUploadVideo
            :videoSrc="authForm.video"
            @uploadSuccess="
              (e) => {
                authForm.video = e.value
              }
            "
            @deleteVideo="authForm.video = ''"
          >
          </cyyUploadVideo>
          <div class="tip">
            请上传小程序的使用视频或图片（至少选择一项上传），必须包括如何登录、如何授权输出此字段、如何使用等内容。
            数量及格式要求 最多上传1个视频，最多上传5张图片，图片格式必须为：png、jpeg、jpg，每张图片不超过10MB。
          </div>
        </a-form-model-item>
        <a-form-model-item label="使用场景" prop="scene_code">
          <a-select style="width: 120px" v-model="authForm.scene_code">
            <a-select-option :value="item.scene_code" v-for="item in fieldList" :key="item.scene_code">
              {{ item.scene_desc }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="接口调用峰值" prop="qps_answer">
          <a-textarea
            placeholder="例如
预计接口秒级调用量峰值：800QPS。"
            :rows="3"
            v-model="authForm.qps_answer"
          />
        </a-form-model-item>
        <a-form-model-item label="处理舆情数量" prop="customer_answer">
          <a-textarea
            placeholder="例如
1.有自己的客服团队，3-5人，能够及时响应并处理舆情
2.无自己的客服渠道"
            :rows="3"
            v-model="authForm.customer_answer"
          />
        </a-form-model-item>
        <a-form-model-item label="备注" prop="memo">
          <a-textarea placeholder="请输入备注" :rows="3" v-model="authForm.memo" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { cyyUploadImg, cyyUploadVideo } from '@/components/CyyUi/index'
import {
  alipayList,
  alipayGetInfo,
  issueAlipay,
  upload,
  alipayCategories,
  alipayInfo,
  alipaySubmit,
  alipayCancleApply,
  rollbackAlipay,
  previewAlipay,
  alipayAddMember,
  cancleExperience,
  promotionAlipay,
  updateAlipay,
  getField,
  aliAuth,
  signContract,
  useAlipayApplet,
} from '@/api/setting/applet'
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 50,
  },
  {
    title: '小程序信息',
    scopedSlots: {
      customRender: 'user',
    },
    width: 260,
  },
  // {
  //   title: '手机号授权状态',
  //   scopedSlots: {
  //     customRender: 'authorization'
  //   }
  // },
  {
    title: '小程序状态',
    scopedSlots: {
      customRender: 'mini_status',
    },
  },
  {
    title: '是/否签约当面付',
    scopedSlots: {
      customRender: 'bind_face',
    },
  },
  {
    title: '是/否使用蚂蚁门店',
    scopedSlots: {
      customRender: 'shop_status',
    },
  },
  {
    title: '是/否使用小程序',
    scopedSlots: {
      customRender: 'is_use',
    },
  },
  {
    title: '是否体验版',
    scopedSlots: {
      customRender: 'experience',
    },
  },
  {
    title: '发布状态',
    scopedSlots: {
      customRender: 'status',
    },
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action',
    },
    width: 200,
  },
]
export default {
  components: {
    cyyUploadImg,
    cyyUploadVideo,
  },

  data() {
    let checkPics = (rule, value, callback) => {
      if (!this.authForm.video && !this.authForm.picture.length) {
        callback(new Error('请上传视频或者照片二选一'))
      } else {
        callback()
      }
    }
    return {
      // 验证规则
      rules: {
        template_id: [{ required: true, message: '请选择小程序模板', trigger: 'change' }],
        user_version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
        user_desc: [{ required: true, message: '请输入小程序代码简介', trigger: 'blur' }],
      },
      queryParam: {
        // 小程序名称
        app_name: '',
        pageNo: 1,
        pageSize: 10,
        is_use: 0,
      },
      // 小程序列表
      list: [],
      // 总数
      totalCount: 0,
      columns,
      // 是否显示提交审核的弹窗
      showCheck: false,
      // 提交审核的表单
      // 展示预览小程序的弹窗
      showPreview: false,
      // 小程序二维码地址
      qrCode: '',
      // 添加体验者的微信号
      wechatId: '',
      // 当前正在修改的小程序
      currentApplet: {},
      // 显示提交代码弹窗
      showUpload: false,
      // 是否加急
      is_fast_audit: 0,
      // 是否显示正式版二维码的弹窗
      showQrcode: false,
      // 显示的二维码地址
      qrcodeUrl: '',
      // 提交审核的小程序表单
      checkForm: {
        id: '',
        version: '',
        version_desc: '',
        app_logo: '',
        app_name: '',
        app_english_name: '',
        mini_category_ids: [],
        service_phone: '',
        service_email: '',
        app_slogan: '',
        app_desc: '',
        license_name: '',
        license_no: '',
        license_pic: '',
        license_date: '',
        is_long_effective: '0',
        other_data: [],
      },
      // 提交审核验证规则
      checkRules: {
        logo: [{ required: true, message: '请上传小程序logo' }],
        version_desc: [{ min: 30, max: 500, required: true, message: '长度30-500字符' }],
        app_name: [{ required: true, message: '请输入小程序名称', trigger: 'blur' }],
        app_english_name: [{ required: true, message: '请输入小程序英文名称', trigger: 'blur' }],
        mini_category_ids: [{ type: 'array', required: true, message: '请选择小程序类目', trigger: 'change' }],
        service_phone: [{ required: true, message: '请输入客服电话', trigger: 'blur' }],
        service_email: [{ required: true, message: '请输入客服邮箱', trigger: 'blur' }],
        app_slogan: [{ required: true, message: '请输入小程序功能描述', trigger: 'blur' }],
        app_desc: [{ required: true, min: 20, max: 200, message: '长度20-200字符', trigger: 'blur' }],
        license_name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        license_no: [{ required: true, message: '请输入企业代码', trigger: 'blur' }],
        license_pic: [{ required: true, message: '请上传营业执照' }],
        license_date: [{ required: true, message: '请选择营业执照过期时间', trigger: 'change' }],
      },
      // 营业执照是否长期
      isLong: 1,
      // 小程序类目
      categories: [],
      // 请求是否在发送中
      isLoading: false,
      // 是否显示授权表单
      showAuthorization: false,
      // 授权手机号的表单
      authForm: {
        video: '',
        picture: [],
        scene_code: '',
        qps_answer: '',
        customer_answer: '',
        memo: '',
      },
      // 敏感信息使用场景
      fieldList: [],
      // 授权信息规则
      authRules: {
        pics: [{ validator: checkPics }],
        scene_code: [{ required: true, message: '请选择隐私信息使用途径', trigger: 'blur' }],
        qps_answer: [{ required: true, message: '请填写接口一年内预计秒级调用量峰值', trigger: 'blur' }],
        customer_answer: [{ required: true, message: '请填写影响和处理舆情数量', trigger: 'blur' }],
        memo: [{ required: true, message: '请填写备注', trigger: 'blur' }],
      },
      batch_status: 0,
      hasChannel: false,
    }
  },

  computed: {
    getStatus() {
      return (status) => {
        let arr = []

        switch (parseInt(status)) {
          case 0:
            arr = ['background-color:#FAAD14;', '未审核']
            break

          case 1:
            arr = ['background-color:#FAAD14;', '审核中']
            break

          case 2:
            arr = ['background-color:#1890FF;', '审核通过']
            break

          case 3:
            arr = ['background-color:#FF4D4F;', '审核失败']
            break

          case 4:
            arr = ['background-color:#65C817;', '已发布']
            break
        }

        return arr
      }
    },

    getShopStatus() {
      return (status) => {
        let arr = []
        switch (parseInt(status)) {
          case 0:
            arr = ['', '未使用']
            break

          case 1:
            arr = ['orange', '审核中']
            break

          case 2:
            arr = ['green', '成功']
            break

          case 3:
            arr = ['red', '失败']
            break
        }

        return arr
      }
    },

    getBindFace() {
      return (status) => {
        let arr = []
        switch (parseInt(status)) {
          case 0:
            arr = ['', '未签约']
            break

          case 1:
            arr = ['green', '已经创建']
            break

          case 2:
            arr = ['green', '已签约']
            break

          case 3:
            arr = ['orange', '审核中']
            break

          case 4:
            arr = ['orange', '异常单']
            break

          case 5:
            arr = ['orange', '待确认']
            break

          case 6:
            arr = ['orange', '商户确认成功']
            break

          case 7:
            arr = ['orange', '商户超时未确认']
            break

          case 8:
            arr = ['red', '审核失败']
            break
        }

        return arr
      }
    },

    getMiniStatus() {
      return (status) => {
        let arr = []
        switch (status) {
          case 1:
            arr = ['green', '已成功']
            break

          case 0:
            arr = ['orange', '待确认']
            break

          case -1:
            arr = ['red', '已拒绝']
            break
        }
        return arr
      }
    },

    batch_text: function () {
      let text = ''
      switch (this.batch_status) {
        case 1:
          text = '已经创建'
          break
        case 2:
          text = '待审核'
          break
        case 3:
          text = '审核中'
          break
        case 4:
          text = '状态异常'
          break
        case 5:
          text = '等待商户确认'
          break
        case 6:
          text = '确认成功'
          break
        case 7:
          text = '超时未确认'
          break
        case 8:
          text = '审核失败'
          break
        default:
          text = '创建事务'
      }
      return text
    },
  },
  methods: {
    see(id) {
      if (this.hasChannel) return this.$router.push('/saasChannel/appletAlipay/writeInformationAlipay?id=' + id)
      this.$router.push('/setting/appletManagement/writeInformationAlipay?id=' + id)
    },

    async faceBind(e) {
      const hide = this.$message.loading('加载中', 0)
      let params = {
        id: e,
      }
      const res = await signContract(params)
      if (res.code == 0) {
        this.$message.success(res.msg)
        this.getList()
      } else {
        this.$message.error(res.msg)
      }
      hide()
    },
    delPic(e) {
      this.checkForm.other_data.splice(e.index, 1)
    },
    selectPic(e) {
      console.log(e)
      let arr = this.checkForm.other_data ? this.checkForm.other_data : []
      console.log(arr)
      let length = arr.length
      if (length >= 3) {
        this.$message.error('最多上传三张特殊资质图片')
      }
      if (length < 3) {
        e.data.splice(3 - length) //
      }

      e.data.forEach((ele) => {
        console.log(ele)
        arr.push(ele)
      })
      this.$set(this.checkForm, 'other_data', arr)
      console.log(this.checkForm.other_data, 'this.checkForm.other_data')
    },
    // 关闭弹窗
    closeModal() {
      this.wechatId = ''
      this.qrCode = ''
    },
    // 获取小程序列表
    async getList() {
      const hide = this.$message.loading('加载中', 0)
      const res = await alipayList(this.queryParam)
      console.log(res)
      if (res.code == 0) {
        this.totalCount = res.totalCount
        this.list = res.data
      }
      hide()
    },
    // 分页请求
    tablePageChange(e) {
      this.queryParam.pageNo = e
      this.getList()
    },
    // 提交审核小程序
    async checkApplet() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.isLoading = true
          const res = await alipaySubmit({ auditData: this.checkForm })
          console.log(res)
          if (res.code == 0) {
            this.showCheck = false
            this.getList()
          }
          this.isLoading = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 点击预览小程序
    async previewAlipay(e) {
      if (e.is_experience == 1) {
        this.currentApplet = e
        this.qrCode = e.experience_url
        this.showPreview = true
      } else {
        const res = await previewAlipay({ id: e.id })
        if (res.code == 0) {
          this.currentApplet = e
          this.qrCode = res.data
          this.showPreview = true
          this.getList()
        }
      }
    },
    // 点击确定添加小程序体验者
    async addPreviewer() {
      if (this.wechatId && this.wechatId != '') {
        const res = await alipayAddMember({ logon_id: this.wechatId, id: this.currentApplet.id, role: 2 })
        if (res.code == 0) {
          this.$message.success('添加成功')
          this.wechatId = ''
        }
      }
    },
    // 点击下载小程序码
    downloadIamge(imgsrc, name) {
      //下载图片地址和图片名
      var image = new Image()
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = function () {
        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        var context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        var url = canvas.toDataURL('image/png') //得到图片的base64编码数据

        var a = document.createElement('a') // 生成一个a元素
        var event = new MouseEvent('click') // 创建一个单击事件
        a.download = name || 'photo' // 设置图片名称
        a.href = url // 将生成的URL设置为a.href属性
        a.dispatchEvent(event) // 触发a的单击事件
      }
      image.src = imgsrc
    },
    // 通过code解析授权信息
    async authorization(auth_code) {
      try {
        const res = await alipayGetInfo({ app_auth_code: auth_code })
        location.replace(location.href.replace(location.hash, `#${this.$route.path}`))
        this.getList()
      } catch (error) {
        this.getList()
        location.replace(location.href.replace(location.hash, `#${this.$route.path}`))
      }
    },
    // 点击发布小程序
    issueAlipay(id) {
      const that = this
      this.$confirm({
        title: '确认发布小程序',
        onOk() {
          issueAlipay({ id }).then((res) => {
            if (res.code == 0) {
              that.getList()
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    // 点击上传代码
    upload(e) {
      this.currentApplet = e
      this.showUpload = true
    },
    // 点击上传代码
    uploadApplet() {
      this.$refs['checkForm'].validate(async (valid) => {
        if (valid) {
          const res = await upload({ ...this.checkForm, id: this.currentApplet.id })
          if (res.code == 0) {
            this.showUpload = false
            this.getList()
          }
        } else {
          return false
        }
      })
    },
    // 获取小程序类目
    async alipayCategories(id) {
      const res = await alipayCategories({
        is_filter: 1,
        id,
      })
      if (res.code == 0) {
        this.categories = res.data
      }
    },
    changeNode(e) {
      if (e.length > 4) {
        this.$message.warning('最多可选4个类目')
        this.checkForm.mini_category_ids = this.checkForm.mini_category_ids.slice(0, 4)
        return
      }
    },
    // 点击审核获取支付宝小程序基础信息
    async alipayInfo(id) {
      this.alipayCategories(id)
      const res = await alipayInfo({ id })
      console.log(res)
      if (res.code == 0) {
        this.checkForm = res.data
        this.showCheck = true
      }
    },
    // 点击取消审核
    cancleApply(id) {
      const that = this
      this.$confirm({
        title: '确认撤回审核？',
        onOk() {
          alipayCancleApply({ id }).then((res) => {
            if (res.code == 0) {
              that.getList()
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    // 点击退回开发
    rollbackAlipay(id) {
      const that = this
      this.$confirm({
        title: '确认退回开发版本？',
        onOk() {
          rollbackAlipay({ id }).then((res) => {
            if (res.code == 0) {
              that.getList()
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    // 点击取消体验版
    cancleExperience(id) {
      const that = this
      this.$confirm({
        title: '确认取消体验版本？',
        onOk() {
          cancleExperience({ id }).then((res) => {
            if (res.code == 0) {
              that.getList()
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    // 点击生成推广二维码
    async promotionAlipay(id) {
      const res = await promotionAlipay({ id })
      if (res.code == 0) {
        this.qrcodeUrl = res.data.qr_code_url
        this.showQrcode = true
      }
    },
    // 点击更新模板
    update(id) {
      const that = this
      this.$confirm({
        title: '确认更新模板？',
        onOk() {
          updateAlipay({ id }).then((res) => {
            if (res.code == 0) {
              that.getList()
              that.showCheck = false
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    // 点击撤销审核
    cancelAudit(id) {
      const that = this
      this.$confirm({
        title: '确认撤销审核？',
        onOk() {
          alipayCancleApply({ id }).then((res) => {
            if (res.code == 0) {
              that.getList()
              that.showCheck = false
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    // 点击显示授权信息
    toAuthorization(e) {
      this.getField(e.id, e.apply_msg)
      this.currentApplet = e
    },
    // 获取敏感信息使用场景
    async getField(id, apply_msg) {
      const hide = this.$message.loading('加载中', 0)
      const res = await getField({ id })
      if (res.code == 0) {
        this.fieldList = res.data
        this.showAuthorization = true
        this.authForm = apply_msg
      }
      hide()
    },
    // 提交授权
    applyAuth() {
      this.$refs.authForm.validate(async (valid) => {
        if (valid) {
          this.isLoading = true
          let param = JSON.parse(JSON.stringify(this.authForm))
          param.id = this.currentApplet.id
          const res = await aliAuth({ apply_msg: param })
          if (res.code == 0) {
            this.showAuthorization = false
            this.getList()
          }
          this.isLoading = false
        } else {
          return false
        }
      })
    },
    // 上传图片成功
    successCb(e) {
      this.authForm.picture = [...this.authForm.picture, ...e.data]
      if (this.authForm.picture.length > 5) {
        this.authForm.picture = this.authForm.picture.slice(0, 4)
      }
    },
    // 删除图片
    deleteCb(e) {
      this.authForm.picture.splice(e.index, 1)
    },
    // 使用小程序
    useApplet(id) {
      const that = this
      this.$confirm({
        title: '确认使用小程序？',
        onOk() {
          useAlipayApplet({ id }).then((res) => {
            if (res.code == 0) {
              that.getList()
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
  },
  mounted() {
    console.log(this.$route.query)
    if (this.$route.query.app_auth_code) {
      this.authorization(this.$route.query.app_auth_code)
    } else {
      this.getList()
    }

    if (this.$route.meta.hasChannel) {
      this.hasChannel = true
    }
  },
}
</script>

<style lang="less" scoped>
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-right: 20px;
  }
  .select {
    display: flex;
    align-items: center;
    margin-right: 20px;
  }
}
.name {
  display: flex;
  align-items: center;
  .pic {
    width: 48px;
    min-width: 48px;
    height: 48px;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .info {
    flex: auto;
    width: 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    span {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      color: rgba(0, 0, 0, 0.45);
      margin-top: 6px;
    }
  }
}
.status {
  display: flex;
  align-items: center;
  span:nth-child(1) {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 4px;
  }
  .gray {
    background-color: #c6c6c6;
  }
  .green {
    background-color: #65c817;
  }
  .red {
    background-color: #ff4d4f;
  }
  .orange {
    background-color: #faad14;
  }
}
.action {
  /deep/ .ant-divider {
    margin: 0;
  }
}
.qrBox {
  display: flex;
  .qrCode {
    width: 300px;
    min-width: 300px;
    height: 300px;
    padding: 20px;
    background-color: #fafafa;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
.formBox {
  width: 100%;
  display: flex;
  .version {
    flex: 1;
  }
  .basic {
    flex: 1;
    height: 400px;
    overflow-y: auto;
  }
}
.tip {
  line-height: normal;
}
</style>
